package com.wjw.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;

/**
 * 获取Sqlsession 工具类：
 */
@Component
public class GetSqlSessionUtils {
    private  static SqlSessionFactory sqlSessionFactory=null;

    static{
        String resource="mybatis-config.xml";
        try {
            //读取配置文件 获取sqlsessionFactory
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            Configuration configuration = sqlSessionFactory.getConfiguration();
            //System.out.println(configuration);
            //Environment environment = configuration.getEnvironment();
            //System.out.println(environment);
            //DataSource dataSource = environment.getDataSource();
            //System.out.println(dataSource);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取sqlSession
     * @return
     */
    public static SqlSession getSqlSession(){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        return sqlSession;
    }
}
